<template>
  <div>
    <el-card style="margin: 0 0 20px 0;">
      <CategorySelect :show="!isShowTable" @getCategoryId="getCategoryId" />
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="attrList.length==0"
          @click="addAttr">添加属性</el-button>
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="100px" />
          <el-table-column prop="attrName" label="属性名称" width="100px" />
          <el-table-column label="属性值列表">
            <template slot-scope="scope">
              <el-tag v-for="attr in scope.row.attrValueList" :key="attr.id" type="success"
                style="margin-right: 10px;">{{ attr.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
              <el-button size="mini" type="warning" icon="el-icon-edit" circle
                @click="updateAttr(scope.row)" />
              <el-button size="mini" type="danger" icon="el-icon-delete" circle />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性|修改属性的结构 -->
      <div v-show="!isShowTable">
        <el-form ref="form" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" />
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrInfo.attrName"
          @click="addAttrValue">添加属性值</el-button>
        <el-button>取消</el-button>
        <el-table style="width: 100%; margin: 20px 0;" border :data="attrInfo.attrValueList">
          <el-table-column align="center" type="index" label="序号" width="80px" />
          <el-table-column label="属性值名称">
            <template slot-scope="{row,$index}">
              <!-- 这里的结构需要span与input来回切换 -->
              <el-input v-if="row.flag" :ref="$index" v-model="row.valueName" size="mini"
                placeholder="请输入属性值名称" @blur="toLook(row)" @keyup.native.enter="toLook(row)" />
              <span v-else style="display: block;"
                @click="toEdit(row,$index)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="">
            <template slot-scope="{row,$index}">
              <!-- 气泡确认框 -->
              <el-popconfirm :title="`确定删除${row.valueName}吗?`" @onConfirm="deleteAttrValue($index)">
                <el-button slot="reference" size="mini" type="danger" icon="el-icon-delete" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" :disabled="attrInfo.attrValueList.length<1"
          @click="addOrUpdateAttr">保存</el-button>
        <el-button @click="isShowTable=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash中的深拷贝
import cloneDeep from 'lodash/cloneDeep';
export default {
  name: 'Attr',
  data() {
    return {
      attrList: [],
      // 这个属性控制表格的显示与隐藏
      isShowTable: true,
      category1Id: '',
      category2Id: '',
      category3Id: '',
      // 收集用户新增|修改属性
      attrInfo: {
        attrName: '', // 属性名
        attrValueList: [
          // 属性名称中属性值，因为可以是多个，需要的是数组
        ],
        categoryId: 0, // 三级分类的id
        categoryLevel: 3, // 因为服务器也要区分几级id
      },
    };
  },
  mounted() {},
  methods: {
    getCategoryId(category1Id, category2Id, category3Id) {
      this.category1Id = category1Id;
      this.category2Id = category2Id;
      this.category3Id = category3Id;
      // console.log(this.category1Id,this.category2Id,this.category3Id);
      this.getAttrList();
    },
    getAttrList() {
      const { category1Id, category2Id, category3Id } = this;
      this.$API.attr
        .reqAttrInfoList(category1Id, category2Id, category3Id)
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.attrList = res.data;
          }
        });
    },
    // 添加属性值按钮的回调，但是点击修改时，不会有flag
    addAttrValue() {
      // 向属性值数组里面添加元素
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, // 添加时没有id，修改时有id
        valueName: '',
        flag: true, // 用于切换显示与隐藏
      });
      // 添加新的属性值也要自动获取焦点,数组最后一个获取焦点
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    // 添加属性按钮的回调
    addAttr() {
      this.isShowTable = false;
      // 清除数据
      // 收集三级分类的id
      this.attrInfo = {
        attrName: '', // 属性名
        attrValueList: [
          // 属性名称中属性值，因为可以是多个，需要的是数组
        ],
        categoryId: this.category3Id, // 三级分类的id
        categoryLevel: 3, // 因为服务器也要区分几级id
      };
    },
    // 修改按钮的回调函数
    updateAttr(row) {
      this.isShowTable = false;
      // 结构比较复杂，需要深拷贝
      this.attrInfo = cloneDeep(row);
      // 在修改时需添加上flag
      this.attrInfo.attrValueList.forEach((item) => {
        // 此处不能这样写，因为不起作用，不是响应式的数据
        // item.flag=false
        // 响应式数据（数据变化，视图跟着变）
        this.$set(item, 'flag', false);
      });
    },
    // 失去焦点或按回车显示span
    toLook(row) {
      if (row.valueName.trim() == '') {
        this.$message('请你输入一个正常的属性值');
        return;
      }
      // 判断添加的时候不能有重复，如果重复，isRepat为布尔值
      const isRepat = this.attrInfo.attrValueList.some((item) => {
        if (row !== item) {
          return item.valueName == row.valueName;
        }
      });
      if (isRepat) {
        this.$message('请你输入一个不重复的属性值');
        return;
      }
      row.flag = false;
    },
    // 点击span显示文本框
    toEdit(row, index) {
      row.flag = true;
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 气泡确认框确定按钮的回调
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    // 保存按钮的回调,进行添加属性和修改属性的操作
    addOrUpdateAttr() {
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (item) => {
          return item.valueName != '';
        }
      );
      // this.$API.attr.reqAddOrUpdateAttr(this.attrInfo).then((res)=>{
      //   if(res.code==200){
      //     this.$message({message: '恭喜你，保存成功',type: 'success'});
      //     this.isShowTable=true,
      //     this.getAttrList()
      //   }
      // })
      try {
        this.$API.attr.reqAddOrUpdateAttr(this.attrInfo).then((res) => {
          this.$message({ message: '恭喜你，保存成功', type: 'success' });
          (this.isShowTable = true), this.getAttrList();
        });
      } catch (error) {
        this.$message.error('保存失败');
      }
    },
  },
};
</script>

<style>
</style>
